﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.Roles;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.Roles
{
    public class GetRoleCommandHandler : IRequestHandler<GetRoleCommand, APIResult<APIPaging<List<RoleDto>>>>
    {
        IBaseRepository<Role> rRep;
        IMapper mapper;
        ILogger<GetRoleCommandHandler> logger;
        public GetRoleCommandHandler(IBaseRepository<Role> rRep, IMapper mapper, ILogger<GetRoleCommandHandler> logger)
        {
            this.rRep = rRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<APIResult<APIPaging<List<RoleDto>>>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = rRep.GetAll().Where(x => !x.IsDel);
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    list = list.Where(x => x.RoleName.Contains(request.RoleName));
                }
                int totalCount = list.Count();
                int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
                list = list.OrderBy(x => x.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                var rDto = mapper.Map<List<RoleDto>>(list);
                return new APIResult<APIPaging<List<RoleDto>>>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "获取角色列表成功",
                    Data = new APIPaging<List<RoleDto>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = rDto
                    }
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
